<?php

namespace app\models;

class Auth extends \core\Model
{
    // 数据表名
    public $table = 'users';
    // 数据表主键
    public $primaryKey  = 'id';

    // 保存用户
    public function save($input)
    {
        $input['password']   = password_hash($input['password'], PASSWORD_DEFAULT);
        $input['created_at'] = time();
        // 'created_ip' => getIp(),

        $result = $this->model->insert($input);

        return $this->findByName($input['username']);
    }

    // 登录用户
    public function login(string $username, string $password)
    {
        $user = $this->findByName($username);

        if ($user && password_verify($password, $user['password'])) {
            return $user;
        }
        
        // return false;
    }

    // 用户名是否存在
    public function findByName(string $name)
    {
        return $this->model->where('username = ?', [$name])->first('id, email, username, password');
    }

    // 用户邮箱是否存在
    public function findByEmail(string $email)
    {
        return $this->model->where('email = ?', $email)->first('id');
    }
}
